package com.wj.algorithm.lintcode;

import com.wj.algorithm.ArrayUtil;

public class P6 {
    
    private int fillData(int[] dist, int distFrom, int[] src, int srcFrom) {
        int count = 0;
        for(int i = srcFrom, len = src.length; i < len; i ++) {
            dist[distFrom] = src[i];
            distFrom ++;
            count ++;
        }
        return count;
    }

    public int[] mergeSortedArray(int[] A, int[] B) {
        int[] rs = new int[0];
        if(A == null && B == null) {
            return rs;
        }
        if(A == null) {
            return B;
        }
        if(B == null) {
            return A;
        }
        int aLen = A.length;
        int bLen = B.length;
        int aIndex = 0;
        int bIndex = 0;
        
        int len = A.length + B.length;
        rs = new int[len];
        int index = 0;
        
        while(aIndex < aLen && bIndex < bLen) {
            int va = A[aIndex];
            int vb = B[bIndex];
            if(va < vb) {
                rs[index] = va;
                aIndex ++;
            } else {
                rs[index] = vb;
                bIndex ++;
            }
            index ++;
        }
        
        index += fillData(rs, index, A, aIndex);
        fillData(rs, index, B, bIndex);
        
        return rs;
    }
    
    
    public static void main(String[] args) {
        System.out.println(ArrayUtil.toString(new P6().mergeSortedArray(new int[]{1,2,3,4}, new int[]{2,4,5,6})));
    }
}
